<?php

/**
 * @Description    组织架构控制器
 * @Author         zhaojiping
 * @Copyright      Copyright (c) 山东艾思软件科技有限公司(https://www.aisisofit.cn)
 * @Date           2022/2/7
 * @CreateBy       VS Code
 */

namespace app\core\controller;

use app\core\model\CoreDepartment;
use app\core\model\CoreTitle;
use app\core\model\CoreUser;
use think\facade\Db;

class DepartmentController extends \app\common\controller\GeneralController {

    /**
     * 初始化
     */
    public function initialize() {
        parent::initialize();
        $this->model = new CoreDepartment();
        $this->validate = new \app\core\validate\CoreDepartment();
    }

    /**
     * 以department_id获取department下的部门和人员
     */
    public function getDepartmentDetail() {
        $department_id = input('department_id/d', 1);

        $data['department'] = $this->model->where(['id' => $department_id])->field('id, name')->find();
        $data['department']['_child'] = $this->model->where(['pid' => $department_id])
            ->field('id, name')
            ->order('sort, id')->select()->toArray();

        $where[] = ['department_id', '=', $department_id];
        $where[] = ['usable', '=', 1];  // 可用的人员
        $data['user'] = Db::name('CoreUser')
            ->where($where)
            ->field('id, nickname, mobile, is_manager')
            ->order('is_manager, id')
            ->select()->toArray();

        json_return(1, '部门详情', $data);
    }

    public function getDepartmentAll() {
        // p(cache('core_department_all'));
        //cache('core_department_all', null); // 测试时打开, 防止修代码无效
        if (!cache('core_department_all')) {
            $DB_PREFIX = config('database.connections.mysql.prefix');
            $departments = Db::query("SELECT id,concat('p',id) as temp_id,`name` as nickname, pid FROM {$DB_PREFIX}core_department order by sort,id");
            foreach ($departments as $k => &$v) {
                $v['leaf'] = false;
                $v['isDisabled'] = true;
            }
            $data = self::departmentTree($departments, 0);
            cache('core_department_all', $data);
        }

        json_return(1, '部门详情', cache('core_department_all'));
    }

    private static function departmentTree($departments, $pid = 0) {
        $DB_PREFIX = config('database.connections.mysql.prefix');
        $children = [];
        foreach ($departments as $department) {
            if ($department['pid'] == $pid) {
                $tmp = self::departmentTree($departments, $department['id']);
                $users = Db::query("select id,concat('u',id) as temp_id,nickname from {$DB_PREFIX}core_user where department_id={$department['id']} order by is_manager, id");
                // p($users);
                foreach ($users as $k => &$v) {
                    $v['leaf'] = true;
                    $v['isDisabled'] = false;
                }
                $department['children'] = array_merge($users, $tmp);
                $children[] = $department;
            }
        }
        return $children;
    }

    /**
     * 列表形式的所有组织架构, 但按分组模式, 含等级
     */
    public function getListsByLevel() {
        $result = $this->model->getList($where = [], $fields = 'id, pid, name, sort,is_system, is_shop');
        // p($result);
        $data = $this->model->getListByLevel($result);

        json_return(1, '组织架构列表', $data);
    }

    /**
     * 列表形式的所有组织架构, 但按分组模式, 含等级, for select
     */
    public function getListsByLevelForSelect() {
        $result = $this->model->getList($where = ' is_shop=0 ', $fields = 'id, pid, name, sort,is_system, is_shop');
        // p($result);
        $data = $this->model->getListByLevel($result);

        json_return(1, '组织架构列表', $data);
    }

    /**
     * 返回树型结构的所有
     */
    public function getDepartmentTree() {
        $result = $this->model->getList($where = [], $fields = 'id, pid, name');
        $list = $this->model->getTree($result);

        json_return(1, '组织架构列表', $list);
    }

    /**
     * APP端组织架构
     */
    public function appDepartments() {
        $pid = input('pid/d', 0);
        $sql = "(
            SELECT a.`id`,a.`nickname` `name`,a.`avatar`,b.`name` title_name, 1 `type`
            FROM ais_core_user a
            LEFT JOIN ais_core_title b ON a.title_id=b.id
            WHERE a.department_id={$pid}
            ) UNION (
            SELECT `id`,`name`,'' avatar,'' title_name, 0 `type`
            FROM ais_core_department
            WHERE pid={$pid}
            )";
        $list = Db::query($sql);
        $defaultAvatar = @cache('config')['org_default_avatar'];
        $defaultDepartmentAvatar = @cache('config')['org_department_avatar'];
        $list = array_map(function ($item) use ($defaultAvatar, $defaultDepartmentAvatar) {
            if ($item['type'] == 1) {
                if (empty($item['avatar'])) {
                    $item['avatar'] = $defaultAvatar;
                } elseif (strpos($item['avatar'], '/static/images/avatar.png') === 0) {
                    $item['avatar'] = 'https://ems-1253777855.cos.ap-guangzhou.myqcloud.com/static/images/avatar.png';
                }
            }
            if ($item['type'] == 2) $item['avatar'] = $defaultDepartmentAvatar;
            return $item;
        }, $list);
        json_return(1, '', $list);
    }

    /**
     * APP端用户信息 
     */
    public function appUserInfo() {
        $uid = input('user_id', 0);
        $emchat_name = input('emchat_name', '');
        $where = [];
        if ($uid) $where[] = ['id', '=', $uid];
        if ($emchat_name) $where[] = ['emchat_name', '=', $emchat_name];
        $user = CoreUser::where($where)->find();
        if (empty($user)) json_return(0, '用户不存在');
        $department = CoreDepartment::find($user->department_id);
        $title = CoreTitle::find($user->title_id);
        json_return(1, '', [
            'id' => $user->id,
            'nickname' => $user->nickname,
            'emchat_name' => $user->emchat_name,
            'mobile' => $user->mobile,
            'department' => $department->name,
            'avatar' =>  $user->avatar,
            'title_name' => @$title->name,
        ]);
    }
}
